﻿#pragma once
#include <memory>
#include <x264.h>

struct H264Encoder
{
	H264Encoder()
	{
		if (param = (x264_param_t*)malloc(sizeof(x264_param_t)))
		{
			memset(param, 0, sizeof(x264_param_t));
		}

		if (picture_in = (x264_picture_t*)malloc(sizeof(x264_picture_t)))
		{
			memset(picture_in, 0, sizeof(x264_picture_t));
		}

		if (picture_out = (x264_picture_t*)malloc(sizeof(x264_picture_t)))
		{
			x264_picture_init(picture_out);
		}

		handle = nullptr;
		nal = nullptr;
		nal_count = -1;
		bit_rate = 1500;
		frame_rate = 60;
	}

	~H264Encoder()
	{
		if (picture_in) {
			free(picture_in);
			picture_in = nullptr;
		}

		if (picture_out)
		{
			free(picture_out);
			picture_out = nullptr;
		}

		if (param) {
			free(param);
			param = nullptr;
		}
	}

	/** 编码器参数设置实体 */
	x264_param_t* param;

	/** 结构体描述一视频帧的特征 */
	x264_picture_t* picture_in;
	x264_picture_t* picture_out;

	/** 编码器句柄 */
	x264_t* handle;

	/** 编码后的数据单元 */
	x264_nal_t* nal;

	/** 编码后的数据单元数量 */
	int nal_count;

	/** 码率 */
	int bit_rate;

	/** 帧率 */
	int frame_rate;
} ;

/** 初始化编码器，并返回一个编码器对象 */
void h264_compress_begin(H264Encoder* en, int width, int height);

/** 编码一帧 */
int h264_encode_frame(H264Encoder* en, uint8_t* in);

/** 释放内存 */
void h264_compress_end(H264Encoder* en);